package activity.addCamera;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hichip.campro.R;
import com.hichip.tools.HiSearchSDK;
import base.HiActivity;
import butterknife.BindView;
import common.HiDataValue;
import common.TitleView;
import main.MainActivity;
import utils.HiToast;
import utils.WifiAdmin;

/**
 * 连接设备热点 界面
 * Created by lt on 2017\12\25 0025.
 */
public class APConnectActivity extends HiActivity implements View.OnClickListener {

    @BindView(R.id.tv_wifi_ssid) TextView tv_wifi_ssid;
    @BindView(R.id.but_connect) Button but_connect;
    @BindView(R.id.et_wifi_password) EditText et_wifi_password;
    @BindView(R.id.titleview) TitleView titleview;

    private String ssid;
    private CountDownTimer timer;
    private HiSearchSDK searchSDK;
    private String mUid;
    private ConnectionChangeReceiver mReceiver;
    private String mCurrentPhoneWiFi;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_ap_connect;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        getIntentData();
        registerRece();
        initView();
        setListeners();

    }

    private void getIntentData() {
        ssid = getIntent().getStringExtra("ssid");
        mCurrentPhoneWiFi = getIntent().getStringExtra("mCurrentPhoneWiFi");
    }

    private void registerRece() {
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        mReceiver = new ConnectionChangeReceiver();
        registerReceiver(mReceiver, filter);
    }


    private void setListeners() {
        but_connect.setOnClickListener(this);
    }

    private void initView() {
        titleview.setButton(TitleView.NAVIGATION_BUTTON_LEFT);
        titleview.setTitle(getString(R.string.title_find_device_spot));
        titleview.setRightTxtBack(R.mipmap.x_bule);
        titleview.setNavigationBarButtonListener(new TitleView.NavigationBarButtonListener() {
            @Override
            public void OnNavigationButtonClick(int which) {
                switch (which) {
                    case TitleView.NAVIGATION_BUTTON_LEFT:
                        APConnectActivity.this.finish();
                        break;
                    case TitleView.NAVIGATION_BUTTON_IV_RIGHT:
                        Intent intent=new Intent(APConnectActivity.this, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        break;
                }
            }
        });
        tv_wifi_ssid.setText(ssid);
        et_wifi_password.setText("01234567");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.but_connect:
                //WIFI操作管理工具类
                WifiAdmin wifiAdmin = new WifiAdmin(getApplicationContext());
                if (!wifiAdmin.mWifiManager.isWifiEnabled()) {
                    //HiToast.showToast(getApplicationContext(),"请打开手机WiFi开关!");//不能加 小米手机要崩
                    return;
                }
                //HiToast.showToast(getApplicationContext(), "请耐心等待大约30秒左右");//不能加 小米手机要崩
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mLoadDialoging != null && mLoadDialoging.isShowing() && !APConnectActivity.this.isFinishing()) {
                            dissmissLoadDialog();
                            HiToast.showToast(getApplicationContext(), getString(R.string.connect_search_fail));
                            View customView = View.inflate(APConnectActivity.this, R.layout.pup_connect_dev_hot_fail, null);
                            PopupWindow pup = new PopupWindow(customView);
                            ColorDrawable cd = new ColorDrawable(-000);
                            pup.setBackgroundDrawable(cd);
                            pup.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
                            pup.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
                            if (APConnectActivity.this.isFinishing()) {
                                cd = null;
                                customView = null;
                                return;
                            }
                            pup.showAtLocation(customView, Gravity.CENTER, 0, 0);
                            TextView tv_know = customView.findViewById(R.id.tv_know);
                            tv_know.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    pup.dismiss();
                                    APConnectActivity.this.finish();
                                }
                            });
                        }
                    }
                }, 40000);
                showLoadDialog(getString(R.string.connecting),false,false);
                //handConnect(wifiAdmin);
                countDownTimer = new CountDownTimer(40000, 10000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        handConnect(wifiAdmin);
                    }
                    @Override
                    public void onFinish() {
                    }
                };
                countDownTimer.start();
                break;
        }
    }

    private CountDownTimer countDownTimer;


    //切换指定WIFI的功能
    private void handConnect(WifiAdmin wifiAdmin) {
        WifiInfo info = wifiAdmin.mWifiInfo;
        //这句代码会导致小米手机多次弹出提示,先注释
        wifiAdmin.disconnectWifi(info.getNetworkId());
        WifiConfiguration tempConfig = wifiAdmin.IsExsits(ssid);
        if (tempConfig != null) {
            boolean isRemoveSucc = wifiAdmin.mWifiManager.removeNetwork(tempConfig.networkId);
            if (!isRemoveSucc) {
                Wificonnect(wifiAdmin);
            }
        }
        wifiAdmin.addNetwork(wifiAdmin.CreateWifiInfo(ssid, et_wifi_password.getText().toString(), 3));
    }

    private void Wificonnect(WifiAdmin wifiAdmin) {
        // 连接到外网
        WifiConfiguration mWifiConfiguration;
        WifiManager mWifiManager = wifiAdmin.mWifiManager;
        String SSID = ssid;
        String password = et_wifi_password.getText().toString();
        //检测指定SSID的WifiConfiguration 是否存在
        WifiConfiguration tempConfig = wifiAdmin.IsExsits(SSID);
        if (tempConfig == null) {
            //创建一个新的WifiConfiguration ，CreateWifiInfo()需要自己实现
            mWifiConfiguration = wifiAdmin.CreateWifiInfo(SSID, password, 3);
            int wcgID = mWifiManager.addNetwork(mWifiConfiguration);
            boolean b = mWifiManager.enableNetwork(wcgID, true);
        } else {
            //发现指定WiFi，并且这个WiFi以前连接成功过
            mWifiConfiguration = tempConfig;
            boolean b = mWifiManager.enableNetwork(mWifiConfiguration.networkId, true);
        }

    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HiDataValue.HANDLE_MESSAGE_SCAN_RESULT:
                    dissmissLoadDialog();
                    HiSearchSDK.HiSearchResult searchResult = (HiSearchSDK.HiSearchResult) msg.obj;
                    if (searchResult != null && !TextUtils.isEmpty(mUid)) {
                        if (countDownTimer != null) {
                            countDownTimer.cancel();
                            countDownTimer = null;
                        }
                        Intent intent = new Intent(APConnectActivity.this, AddAndConfigWiFiActivity.class);
                        intent.putExtra(HiDataValue.EXTRAS_KEY_UID, mUid);
                        intent.putExtra("ssid", ssid);
                        intent.putExtra("type", 2);
                        intent.putExtra("mCurrentPhoneWiFi", mCurrentPhoneWiFi);
                        intent.putExtra("isAP", true);
                        startActivity(intent);
                        APConnectActivity.this.finish();
                    }
                    break;

            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        if (searchSDK != null) {
            searchSDK.stop();
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        dissmissLoadDialog();
    }


    private void startSearch() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        int timeLong = 40000;
        searchSDK = new HiSearchSDK(new HiSearchSDK.ISearchResult() {
            @Override
            public void onReceiveSearchResult(HiSearchSDK.HiSearchResult result) {
                String temp = result.uid.substring(0, 4);
                if (!TextUtils.isEmpty(temp)) {
                    Message msg = mHandler.obtainMessage();
                    msg.obj = result;
                    msg.what = HiDataValue.HANDLE_MESSAGE_SCAN_RESULT;
                    mUid = result.uid;
                    mHandler.sendMessage(msg);
                }
            }
        });
        searchSDK.search2();
        timer = new CountDownTimer(timeLong, 1000) {
            @Override
            public void onFinish() {
                if (TextUtils.isEmpty(mUid)) {
                    dissmissLoadDialog();
                    APConnectActivity.this.finish();
                    HiToast.showToast(APConnectActivity.this, getString(R.string.connect_search_fail));
                }
            }

            @Override
            public void onTick(long arg0) {

            }
        }.start();
    }

    public class ConnectionChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (wifiInfo != null && wifiInfo.isAvailable() && wifiInfo.isConnected()) {
                WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
                WifiInfo wifi = wifiManager.getConnectionInfo();
                if (wifi.getSSID().contains(ssid)) {
                    startSearch();
                }
            } else {

            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
    }
}
